<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRpaStore } from '@/stores/rpa'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, Plus } from '@element-plus/icons-vue'
import ApiService from '@/services/ApiService'
import { formatDateTime } from '@/utils/dateFormat'

const rpaStore = useRpaStore()
const currentPage = ref(1)
const pageSize = ref(15)
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentAction = ref('')
const actionResult = ref({})
const actionLoading = ref(false)
const currentRow = ref(null)

// 表单数据
const editForm = ref({
  id: '',
  name: '',
  ip: '',
  status: '',
  version: '',
  systemInfo: {
    cpu: '',
    memory: '',
    disk: ''
  }
})

onMounted(() => {
  rpaStore.fetchRobots()
})

// Compute paginated data
const paginatedRobots = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return rpaStore.robots.slice(start, end)
})

// Calculate total pages
const total = computed(() => rpaStore.robots.length)

// 操作按钮配置
const getActionButtons = (row) => [
  {
    name: 'view',
    label: '详情',
    type: 'primary',
    action: '查看机器人详情',
    size: 'small'
  },
  {
    name: 'edit',
    label: '编辑',
    type: 'warning',
    action: '编辑机器人',
    size: 'small'
  },
  {
    name: 'connect',
    label: '连接',
    type: 'success',
    action: '连接机器人',
    size: 'small'
  },
  {
    name: 'restart',
    label: '重启',
    type: 'danger',
    action: '重启机器人',
    size: 'small'
  }
]

// 处理按钮点击事件
const handleButtonAction = (action, row) => {
  currentRow.value = row
  
  switch (action) {
    case '查看机器人详情':
      handleViewDetails(row)
      break
    case '编辑机器人':
      handleEditRobot(row)
      break
    case '连接机器人':
      handleConnect(row)
      break
    case '重启机器人':
      handleRestart(row)
      break
  }
}

// 添加机器人
const handleAddRobot = () => {
  editForm.value = {
    id: '',
    name: '新机器人',
    ip: '192.168.1.100',
    status: '离线',
    version: '1.0.0',
    systemInfo: {
      cpu: '0%',
      memory: '0%',
      disk: '0%'
    }
  }
  
  currentAction.value = '添加机器人'
  editDialogVisible.value = true
}

// 编辑机器人
const handleEditRobot = (robot) => {
  editForm.value = {
    id: robot.id || '',
    name: robot.name || '',
    ip: robot.ip || '',
    status: robot.status || '',
    version: robot.version || '',
    systemInfo: {
      cpu: robot.systemInfo?.cpu || '0%',
      memory: robot.systemInfo?.memory || '0%',
      disk: robot.systemInfo?.disk || '0%'
    }
  }
  
  currentAction.value = '编辑机器人'
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = () => {
  actionLoading.value = true
  
  ApiService.callApi(
    currentAction.value, 
    editForm.value, 
    (result) => {
      actionResult.value = result
      actionLoading.value = false
      editDialogVisible.value = false
      dialogVisible.value = true
    },
    (error) => {
      actionLoading.value = false
    }
  )
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
}

// 查看机器人详情
const handleViewDetails = (robot) => {
  actionLoading.value = true
  currentAction.value = '查看机器人详情'
  
  ApiService.callApi(
    currentAction.value, 
    robot, 
    (result) => {
      actionResult.value = result
      actionLoading.value = false
      dialogVisible.value = true
    },
    (error) => {
      actionLoading.value = false
    }
  )
}

// 连接机器人
const handleConnect = (robot) => {
  actionLoading.value = true
  currentAction.value = '连接机器人'
  
  ApiService.callApi(
    currentAction.value, 
    robot, 
    (result) => {
      actionResult.value = result
      actionLoading.value = false
      dialogVisible.value = true
    },
    (error) => {
      actionLoading.value = false
    }
  )
}

// 重启机器人
const handleRestart = (robot) => {
  ElMessageBox.confirm(`确定要重启机器人"${robot.name}"吗?`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    actionLoading.value = true
    currentAction.value = '重启机器人'
    
    ApiService.callApi(
      currentAction.value, 
      robot, 
      (result) => {
        actionResult.value = result
        actionLoading.value = false
        dialogVisible.value = true
      },
      (error) => {
        actionLoading.value = false
      }
    )
  }).catch(() => {
    // 用户取消操作
  })
}

// Handle page change
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 在需要格式化时间的地方使用formatDateTime
const formatDate = (date) => {
  return formatDateTime(date)
}
</script>

<template>
  <el-card class="robot-list-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" @click="handleAddRobot">
          <el-icon style="margin-right: 5px;"><Plus /></el-icon>添加机器人
        </el-button>
      </div>
    </template>
    
    <div class="card-body">
      <!-- Loading spinner -->
      <div v-if="rpaStore.loading" class="loading-container">
        <el-icon class="is-loading"><loading /></el-icon>
        <span class="loading-text">加载中...</span>
      </div>
      
      <!-- Error message -->
      <el-alert
        v-if="rpaStore.error"
        :title="rpaStore.error"
        type="error"
        show-icon
      />
      
      <!-- RPA Robots Table -->
      <div v-else class="table-container">
        <el-table :data="paginatedRobots" style="width: 100%" :max-height="600">
          <el-table-column prop="name" label="机器人名称" />
          <el-table-column prop="ip" label="IP地址" width="140" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '在线' ? 'success' : 
                scope.row.status === '离线' ? 'danger' : 'warning'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本" width="100" />
          <el-table-column prop="lastActiveTime" label="最后活动时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.lastActiveTime) }}
            </template>
          </el-table-column>
          <el-table-column label="系统状态" width="180">
            <template #default="scope">
              <div>CPU: {{ scope.row.systemInfo.cpu }}</div>
              <div>内存: {{ scope.row.systemInfo.memory }}</div>
              <div>硬盘: {{ scope.row.systemInfo.disk }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  v-for="button in getActionButtons(scope.row)"
                  :key="button.name"
                  :type="button.type"
                  :size="button.size"
                  :loading="actionLoading && currentAction === button.action && currentRow === scope.row"
                  @click="handleButtonAction(button.action, scope.row)"
                >
                  {{ button.label }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 15, 20, 50]"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        @size-change="size => { pageSize = size; currentPage = 1; }"
        prev-text="上一页"
        next-text="下一页"
        :pager-count="5"
      />
    </div>
  </el-card>
  
  <!-- 操作结果展示对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="currentAction + '结果'"
    width="50%"
    :append-to-body="true"
    :top="'10vh'"
  >
    <div v-if="actionResult.success" class="action-result">
      <el-alert
        title="操作成功"
        type="success"
        :description="actionResult.message"
        show-icon
        :closable="false"
        class="result-alert"
      />
      
      <div class="result-data">
        <h4>响应数据:</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item 
            v-for="(value, key) in actionResult.data" 
            :key="key" 
            :label="key"
          >
            <span v-if="typeof value !== 'object'">{{ value }}</span>
            <div v-else>
              <div v-for="(subVal, subKey) in value" :key="subKey">
                <strong>{{ subKey }}:</strong> 
                <span v-if="!Array.isArray(subVal)">{{ subVal }}</span>
                <div v-else>
                  <ul>
                    <li v-for="(item, idx) in subVal" :key="idx">{{ item }}</li>
                  </ul>
                </div>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
    
    <div v-else class="action-result">
      <el-alert
        title="操作失败"
        type="error"
        :description="actionResult.message"
        show-icon
        :closable="false"
        class="result-alert"
      />
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 编辑机器人对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    :title="currentAction === '添加机器人' ? '添加机器人' : '编辑机器人'"
    width="50%"
    :append-to-body="true"
    :top="'10vh'"
  >
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="机器人名称">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="IP地址">
        <el-input v-model="editForm.ip" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="在线" value="在线" />
          <el-option label="离线" value="离线" />
          <el-option label="维护中" value="维护中" />
        </el-select>
      </el-form-item>
      <el-form-item label="版本">
        <el-input v-model="editForm.version" />
      </el-form-item>
      <el-form-item label="CPU使用率">
        <el-input v-model="editForm.systemInfo.cpu" />
      </el-form-item>
      <el-form-item label="内存使用率">
        <el-input v-model="editForm.systemInfo.memory" />
      </el-form-item>
      <el-form-item label="硬盘使用率">
        <el-input v-model="editForm.systemInfo.disk" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="submitEditForm" :loading="actionLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.robot-list-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.card-body {
  flex: 1;
  overflow: auto;
  position: relative;
  padding-bottom: 70px; /* 为分页器留出更多空间 */
}

.table-container {
  height: 100%;
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container .el-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.loading-text {
  color: #909399;
}

.pagination-container {
  position: absolute;
  bottom: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: white;
  z-index: 10;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 2px;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow-x: auto;
}

.action-buttons::-webkit-scrollbar {
  display: none;
}

.action-buttons {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.action-buttons .el-button--small {
  padding: 5px 10px;
  font-size: 12px;
  height: 28px;
  line-height: 1;
  margin-left: 0;
  margin-right: 3px;
}

.action-result {
  padding: 10px;
}

.result-alert {
  margin-bottom: 20px;
}

.result-data {
  margin-top: 20px;
}

.result-data h4 {
  margin-bottom: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.card-header .el-button--large {
  padding: 12px 20px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.3s;
}

.card-header .el-button--large:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
</style> 